package org.melanesia.converters.java;

import java.io.Reader;
import java.sql.Clob;

import org.melanesia.converters.JavaToJavaConverter;
import org.melanesia.converters.exceptions.ConversionException;

/**
 * Converts Clob to a String representing this clob's content.
 *
 * @author marcin.kielar
 */
public final class ClobToStringConverter implements JavaToJavaConverter {

    /**
     * Buffer size for clob stream reading.
     */
    private static final int BUFFER_SIZE = 1024;

    @Override
    public Object convert(final Object value) throws ConversionException {
        try {
            Clob clob = (Clob) value;

            if (clob == null) {
                return null;
            }

            Reader reader = clob.getCharacterStream();

            char[] buffer = new char[BUFFER_SIZE];
            StringBuilder sb = new StringBuilder();

            while (true) {
                int cnt = reader.read(buffer);
                if (cnt < 0) {
                    break;
                }
                sb.append(buffer, 0, cnt);
            }

            return sb.toString();
        } catch (Throwable t) {
            throw new ConversionException(t.getMessage(), t);
        }
    }
};
